package com.example.service.impl;

import com.example.domain.dto.pricing.ItemDiscountRuleDTO;
import com.example.domain.dto.pricing.PricingRuleDTO;
import com.example.domain.dto.pricing.ThresholdDiscountRuleDTO;
import com.example.domain.entity.ItemDiscountRule;
import com.example.domain.entity.PricingRule;
import com.example.domain.entity.ThresholdDiscountRule;
import com.example.domain.entity.enums.PricingRuleType;
import com.example.domain.repository.ItemDiscountRuleRepository;
import com.example.domain.repository.PricingRuleRepository;
import com.example.domain.repository.ProductRepository;
import com.example.domain.repository.ThresholdDiscountRuleRepository;
import com.example.domain.valueobject.DiscountResult;
import com.example.domain.valueobject.Money;
import com.example.exception.BusinessException;
import com.example.exception.ErrorCode;
import com.example.exception.ResourceNotFoundException;
import com.example.service.PricingService;
import com.example.service.PromotionService;
import com.example.util.IdGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 促销服务实现类
 * 
 * @author Means
 * @since 2025-10-27
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PromotionServiceImpl implements PromotionService {
    
    private final PricingRuleRepository pricingRuleRepository;
    private final ItemDiscountRuleRepository itemDiscountRuleRepository;
    private final ThresholdDiscountRuleRepository thresholdDiscountRuleRepository;
    private final ProductRepository productRepository;
    private final PricingService pricingService;
    
    // ========== 单品折扣规则管理 ==========
    
    @Override
    @Transactional
    public ItemDiscountRuleDTO createItemDiscount(String name, String productId,
                                                  BigDecimal discountRate, Integer priority,
                                                  LocalDateTime validFrom, LocalDateTime validTo) {
        log.info("创建单品折扣规则: name={}, productId={}, discountRate={}", name, productId, discountRate);
        
        // 验证商品存在
        productRepository.findByIdAndNotDeleted(productId)
                .orElseThrow(() -> new ResourceNotFoundException("商品", productId));
        
        // 验证折扣率
        if (discountRate.compareTo(BigDecimal.ZERO) <= 0 || discountRate.compareTo(BigDecimal.ONE) > 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "折扣率必须在(0,1]之间");
        }
        
        // 验证时间范围
        if (validTo != null && validTo.isBefore(validFrom)) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "生效结束时间不能早于开始时间");
        }
        
        // 创建基础促销规则
        PricingRule pricingRule = new PricingRule();
        pricingRule.setId(IdGenerator.generate());
        pricingRule.setName(name);
        pricingRule.setType(PricingRuleType.ITEM_DISCOUNT);
        pricingRule.setPriority(priority);
        pricingRule.setEnabled(false);  // 默认禁用，避免自动生效导致冲突
        pricingRule.setValidFrom(validFrom);
        pricingRule.setValidTo(validTo);
        pricingRule.setIsDeleted(false);
        pricingRule.setCreatedAt(LocalDateTime.now());
        pricingRule.setUpdatedAt(LocalDateTime.now());
        
        pricingRuleRepository.save(pricingRule);
        
        // 创建单品折扣规则
        ItemDiscountRule itemDiscount = new ItemDiscountRule();
        itemDiscount.setId(IdGenerator.generate());
        itemDiscount.setRuleId(pricingRule.getId());
        itemDiscount.setProductId(productId);
        itemDiscount.setDiscountRate(discountRate);
        itemDiscount.setIsDeleted(false);
        itemDiscount.setCreatedAt(LocalDateTime.now());
        itemDiscount.setUpdatedAt(LocalDateTime.now());
        
        itemDiscountRuleRepository.save(itemDiscount);
        
        log.info("单品折扣规则创建成功: ruleId={}, itemDiscountId={}", pricingRule.getId(), itemDiscount.getId());
        
        return ItemDiscountRuleDTO.from(itemDiscount);
    }
    
    @Override
    @Transactional
    public ItemDiscountRuleDTO updateItemDiscountRate(String ruleId, String itemDiscountId, BigDecimal discountRate) {
        log.info("更新单品折扣率: ruleId={}, itemDiscountId={}, newRate={}", ruleId, itemDiscountId, discountRate);
        
        // 验证折扣率
        if (discountRate.compareTo(BigDecimal.ZERO) <= 0 || discountRate.compareTo(BigDecimal.ONE) > 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "折扣率必须在(0,1]之间");
        }
        
        // 查询单品折扣规则
        ItemDiscountRule itemDiscount = itemDiscountRuleRepository.findByIdAndNotDeleted(itemDiscountId)
                .orElseThrow(() -> new ResourceNotFoundException("单品折扣规则", itemDiscountId));
        
        // 验证规则ID匹配
        if (!itemDiscount.getRuleId().equals(ruleId)) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "规则ID不匹配");
        }
        
        // 更新折扣率
        itemDiscount.setDiscountRate(discountRate);
        itemDiscount.setUpdatedAt(LocalDateTime.now());
        
        itemDiscountRuleRepository.save(itemDiscount);
        
        log.info("单品折扣率更新成功: itemDiscountId={}", itemDiscountId);
        
        return ItemDiscountRuleDTO.from(itemDiscount);
    }
    
    @Override
    @Transactional
    public void deleteItemDiscount(String ruleId) {
        log.info("删除单品折扣规则: ruleId={}", ruleId);
        
        // 软删除促销规则
        PricingRule pricingRule = pricingRuleRepository.findByIdAndNotDeleted(ruleId)
                .orElseThrow(() -> new ResourceNotFoundException("促销规则", ruleId));
        
        pricingRule.setIsDeleted(true);
        pricingRule.setUpdatedAt(LocalDateTime.now());
        pricingRuleRepository.save(pricingRule);
        
        // 软删除关联的单品折扣规则
        List<ItemDiscountRule> itemDiscounts = itemDiscountRuleRepository.findByRuleIdAndIsDeleted(ruleId, false);
        for (ItemDiscountRule itemDiscount : itemDiscounts) {
            itemDiscount.setIsDeleted(true);
            itemDiscount.setUpdatedAt(LocalDateTime.now());
        }
        itemDiscountRuleRepository.saveAll(itemDiscounts);
        
        log.info("单品折扣规则删除成功: ruleId={}, 删除了{}条单品折扣", ruleId, itemDiscounts.size());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<ItemDiscountRuleDTO> getItemDiscountsByProduct(String productId) {
        log.debug("查询商品的折扣规则: productId={}", productId);
        
        // 查询商品的单品折扣规则
        List<ItemDiscountRule> itemDiscounts = itemDiscountRuleRepository.findByProductIdAndIsDeleted(productId, false);
        
        // 过滤出有效的规则（关联的促销规则必须启用且在有效期内）
        LocalDateTime now = LocalDateTime.now();
        return itemDiscounts.stream()
                .filter(itemDiscount -> {
                    PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(itemDiscount.getRuleId()).orElse(null);
                    return rule != null && rule.getEnabled() 
                            && !rule.getValidFrom().isAfter(now)
                            && (rule.getValidTo() == null || !rule.getValidTo().isBefore(now));
                })
                .map(ItemDiscountRuleDTO::from)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<ItemDiscountRuleDTO> getAllItemDiscounts() {
        log.debug("查询所有单品折扣规则");
        
        // 查询所有未删除的单品折扣规则
        List<ItemDiscountRule> itemDiscounts = itemDiscountRuleRepository.findByIsDeleted(false);
        
        // 只要关联的促销规则存在且未删除即可（不过滤启用状态和有效期，用于管理界面展示）
        return itemDiscounts.stream()
                .filter(itemDiscount -> {
                    PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(itemDiscount.getRuleId()).orElse(null);
                    return rule != null;
                })
                .map(ItemDiscountRuleDTO::from)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public BigDecimal getBestDiscountRateForProduct(String productId) {
        log.debug("获取商品最优折扣率: productId={}", productId);
        
        List<ItemDiscountRuleDTO> discounts = getItemDiscountsByProduct(productId);
        
        if (discounts.isEmpty()) {
            return null;
        }
        
        // 返回最小的折扣率（最优惠）
        return discounts.stream()
                .map(ItemDiscountRuleDTO::getDiscountRate)
                .min(BigDecimal::compareTo)
                .orElse(null);
    }
    
    // ========== 满减折扣规则管理 ==========
    
    @Override
    @Transactional
    public ThresholdDiscountRuleDTO createThresholdDiscount(String name, BigDecimal thresholdAmount,
                                                           BigDecimal discountAmount, Boolean stackable,
                                                           Boolean thresholdUseOriginalPrice,
                                                           Integer priority, LocalDateTime validFrom,
                                                           LocalDateTime validTo) {
        log.info("创建满减折扣规则: name={}, threshold={}, discount={}, stackable={}, useOriginalPrice={}", 
                name, thresholdAmount, discountAmount, stackable, thresholdUseOriginalPrice);
        
        // 验证金额
        if (thresholdAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "门槛金额必须大于0");
        }
        if (discountAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "减免金额必须大于0");
        }
        if (discountAmount.compareTo(thresholdAmount) >= 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "减免金额不能大于等于门槛金额");
        }
        
        // 验证时间范围
        if (validTo != null && validTo.isBefore(validFrom)) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "生效结束时间不能早于开始时间");
        }
        
        // 创建基础促销规则
        PricingRule pricingRule = new PricingRule();
        pricingRule.setId(IdGenerator.generate());
        pricingRule.setName(name);
        pricingRule.setType(PricingRuleType.THRESHOLD_DISCOUNT);
        pricingRule.setPriority(priority != null ? priority : 3);  // 默认Priority 3
        pricingRule.setEnabled(false);  // 默认禁用，避免自动生效导致冲突
        pricingRule.setValidFrom(validFrom);
        pricingRule.setValidTo(validTo);
        pricingRule.setIsDeleted(false);
        pricingRule.setCreatedAt(LocalDateTime.now());
        pricingRule.setUpdatedAt(LocalDateTime.now());
        
        pricingRuleRepository.save(pricingRule);
        
        // 创建满减折扣规则
        ThresholdDiscountRule thresholdDiscount = new ThresholdDiscountRule();
        thresholdDiscount.setId(IdGenerator.generate());
        thresholdDiscount.setRuleId(pricingRule.getId());
        thresholdDiscount.setThresholdAmount(thresholdAmount);
        thresholdDiscount.setDiscountAmount(discountAmount);
        thresholdDiscount.setStackable(stackable != null ? stackable : Boolean.FALSE);
        thresholdDiscount.setThresholdUseOriginalPrice(thresholdUseOriginalPrice != null ? thresholdUseOriginalPrice : Boolean.FALSE);
        thresholdDiscount.setIsDeleted(false);
        thresholdDiscount.setCreatedAt(LocalDateTime.now());
        thresholdDiscount.setUpdatedAt(LocalDateTime.now());
        
        thresholdDiscountRuleRepository.save(thresholdDiscount);
        
        log.info("满减折扣规则创建成功: ruleId={}, thresholdDiscountId={}", pricingRule.getId(), thresholdDiscount.getId());
        
        return ThresholdDiscountRuleDTO.from(thresholdDiscount);
    }
    
    @Override
    @Transactional
    public ThresholdDiscountRuleDTO updateThresholdDiscount(String ruleId, String thresholdDiscountId,
                                                           BigDecimal thresholdAmount, BigDecimal discountAmount) {
        log.info("更新满减折扣: ruleId={}, thresholdDiscountId={}, newThreshold={}, newDiscount={}", 
                ruleId, thresholdDiscountId, thresholdAmount, discountAmount);
        
        // 验证金额
        if (thresholdAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "门槛金额必须大于0");
        }
        if (discountAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "减免金额必须大于0");
        }
        if (discountAmount.compareTo(thresholdAmount) >= 0) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "减免金额不能大于等于门槛金额");
        }
        
        // 查询满减折扣规则
        ThresholdDiscountRule thresholdDiscount = thresholdDiscountRuleRepository.findByIdAndNotDeleted(thresholdDiscountId)
                .orElseThrow(() -> new ResourceNotFoundException("满减折扣规则", thresholdDiscountId));
        
        // 验证规则ID匹配
        if (!thresholdDiscount.getRuleId().equals(ruleId)) {
            throw new BusinessException(ErrorCode.PARAMETER_ERROR, "规则ID不匹配");
        }
        
        // 更新金额
        thresholdDiscount.setThresholdAmount(thresholdAmount);
        thresholdDiscount.setDiscountAmount(discountAmount);
        thresholdDiscount.setUpdatedAt(LocalDateTime.now());
        
        thresholdDiscountRuleRepository.save(thresholdDiscount);
        
        log.info("满减折扣更新成功: thresholdDiscountId={}", thresholdDiscountId);
        
        return ThresholdDiscountRuleDTO.from(thresholdDiscount);
    }
    
    @Override
    @Transactional
    public void deleteThresholdDiscount(String ruleId) {
        log.info("删除满减折扣规则: ruleId={}", ruleId);
        
        // 软删除促销规则
        PricingRule pricingRule = pricingRuleRepository.findByIdAndNotDeleted(ruleId)
                .orElseThrow(() -> new ResourceNotFoundException("促销规则", ruleId));
        
        pricingRule.setIsDeleted(true);
        pricingRule.setUpdatedAt(LocalDateTime.now());
        pricingRuleRepository.save(pricingRule);
        
        // 软删除关联的满减折扣规则
        List<ThresholdDiscountRule> thresholdDiscounts = thresholdDiscountRuleRepository.findByRuleIdAndIsDeleted(ruleId, false);
        for (ThresholdDiscountRule thresholdDiscount : thresholdDiscounts) {
            thresholdDiscount.setIsDeleted(true);
            thresholdDiscount.setUpdatedAt(LocalDateTime.now());
        }
        thresholdDiscountRuleRepository.saveAll(thresholdDiscounts);
        
        log.info("满减折扣规则删除成功: ruleId={}, 删除了{}条满减折扣", ruleId, thresholdDiscounts.size());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<ThresholdDiscountRuleDTO> getAllThresholdDiscounts() {
        log.debug("查询所有满减折扣规则（包括未启用的）");
        
        // 查询所有未删除的满减折扣规则
        List<ThresholdDiscountRule> thresholdDiscounts = thresholdDiscountRuleRepository.findByIsDeleted(false);
        
        // 过滤出关联的促销规则存在的记录（用于管理后台）
        return thresholdDiscounts.stream()
                .filter(thresholdDiscount -> {
                    PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(thresholdDiscount.getRuleId()).orElse(null);
                    return rule != null;
                })
                .map(ThresholdDiscountRuleDTO::from)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<ThresholdDiscountRuleDTO> getEffectiveThresholdDiscounts() {
        log.debug("查询当前生效的满减折扣规则");
        
        // 查询所有未删除的满减折扣规则
        List<ThresholdDiscountRule> thresholdDiscounts = thresholdDiscountRuleRepository.findByIsDeleted(false);
        
        // 过滤出有效的规则（关联的促销规则必须启用且在有效期内）
        LocalDateTime now = LocalDateTime.now();
        return thresholdDiscounts.stream()
                .filter(thresholdDiscount -> {
                    PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(thresholdDiscount.getRuleId()).orElse(null);
                    if (rule == null) {
                        return false;
                    }
                    // 必须启用
                    if (!Boolean.TRUE.equals(rule.getEnabled())) {
                        return false;
                    }
                    // 必须在有效期内
                    if (rule.getValidFrom() != null && rule.getValidFrom().isAfter(now)) {
                        return false;
                    }
                    if (rule.getValidTo() != null && rule.getValidTo().isBefore(now)) {
                        return false;
                    }
                    return true;
                })
                .map(ThresholdDiscountRuleDTO::from)
                .collect(Collectors.toList());
    }
    // ========== 促销规则通用管理 ==========
    
    @Override
    @Transactional
    public void enableRule(String ruleId) {
        log.info("启用促销规则: ruleId={}", ruleId);
        
        PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(ruleId)
                .orElseThrow(() -> new ResourceNotFoundException("促销规则", ruleId));
        
        // 排他性逻辑：禁用同优先级、同对象的其他规则
        if (rule.getType() == PricingRuleType.ITEM_DISCOUNT) {
            // 单品折扣：禁用同商品的其他折扣
            disableConflictingItemDiscounts(ruleId, rule.getPriority());
            
        } else if (rule.getType() == PricingRuleType.THRESHOLD_DISCOUNT) {
            // 满减：禁用同优先级的其他满减
            disableConflictingThresholdDiscounts(ruleId, rule.getPriority());
        }
        
        // 启用当前规则
        rule.setEnabled(true);
        rule.setUpdatedAt(LocalDateTime.now());
        
        pricingRuleRepository.save(rule);
        
        log.info("促销规则已启用: ruleId={}", ruleId);
    }
    
    @Override
    @Transactional
    public void disableRule(String ruleId) {
        log.info("禁用促销规则: ruleId={}", ruleId);
        
        PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(ruleId)
                .orElseThrow(() -> new ResourceNotFoundException("促销规则", ruleId));
        
        rule.setEnabled(false);
        rule.setUpdatedAt(LocalDateTime.now());
        
        pricingRuleRepository.save(rule);
        
        log.info("促销规则已禁用: ruleId={}", ruleId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public PricingRuleDTO getRuleById(String ruleId) {
        log.debug("查询促销规则: ruleId={}", ruleId);
        
        PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(ruleId)
                .orElseThrow(() -> new ResourceNotFoundException("促销规则", ruleId));
        
        return PricingRuleDTO.from(rule);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<PricingRuleDTO> getAllRules() {
        log.debug("查询所有促销规则");
        
        List<PricingRule> rules = pricingRuleRepository.findByIsDeleted(false);
        
        return rules.stream()
                .map(PricingRuleDTO::from)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<PricingRuleDTO> getCurrentEffectiveRules() {
        log.debug("查询当前生效的促销规则");
        
        List<PricingRule> rules = pricingRuleRepository.findAllCurrentEffectiveRules();
        
        return rules.stream()
                .map(PricingRuleDTO::from)
                .collect(Collectors.toList());
    }
    
    // ========== 折扣计算服务 ==========
    
    @Override
    @Transactional(readOnly = true)
    public DiscountResult calculateItemDiscount(String productId, BigDecimal originalAmount) {
        log.debug("计算商品单品折扣: productId={}, originalAmount={}", productId, originalAmount);
        
        if (originalAmount == null || originalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return DiscountResult.noDiscount(originalAmount);
        }
        
        // 获取该商品的所有折扣规则
        List<ItemDiscountRuleDTO> discounts = getItemDiscountsByProduct(productId);
        
        if (discounts.isEmpty()) {
            // 没有折扣，返回原价
            return DiscountResult.noDiscount(originalAmount);
        }
        
        // 业务规则：同一商品同一时间只能有一个折扣生效
        if (discounts.size() > 1) {
            log.error("商品存在多个生效的折扣规则，数据异常: productId={}, count={}, rules={}", 
                     productId, discounts.size(), 
                     discounts.stream().map(ItemDiscountRuleDTO::getId).collect(Collectors.toList()));
            throw new BusinessException(ErrorCode.DISCOUNT_CALCULATION_ERROR, 
                    String.format("商品[%s]存在%d个折扣规则冲突，请联系管理员", productId, discounts.size()));
        }
        
        ItemDiscountRuleDTO discount = discounts.get(0);
        
        // 委托PricingService计算折扣后金额
        Money originalMoney = Money.of(originalAmount);
        Money discountedMoney = pricingService.applyDiscountRate(originalMoney, discount.getDiscountRate());
        BigDecimal discountedAmount = discountedMoney.getDisplayAmount();
        
        // 生成折扣描述（如"8折"）
        String description = generateItemDiscountDescription(discount.getDiscountRate());
        
        log.debug("单品折扣计算结果: originalAmount={}, rate={}, discountedAmount={}, description='{}'",
                originalAmount, discount.getDiscountRate(), discountedAmount, description);
        
        return DiscountResult.withDiscount(originalAmount, discountedAmount, description,
                                         discount.getId(), discount.getPricingRuleId(), "PERCENTAGE");
    }
    
    /**
     * 生成单品折扣描述
     * 
     * @param discountRate 折扣率（如0.8表示8折）
     * @return 折扣描述字符串
     */
    private String generateItemDiscountDescription(BigDecimal discountRate) {
        if (discountRate == null) {
            return "";
        }
        
        // 将折扣率转换为折数（如0.8 -> 8折）
        BigDecimal fold = discountRate.multiply(new BigDecimal("10"))
                .setScale(1, RoundingMode.HALF_UP)
                .stripTrailingZeros();
        
        return fold.toPlainString() + "折";
    }
    
    @Override
    @Transactional(readOnly = true)
    public DiscountResult calculateThresholdDiscount(BigDecimal currentSubtotal, BigDecimal originalSubtotal) {
        log.debug("计算满减折扣: currentSubtotal={}, originalSubtotal={}", currentSubtotal, originalSubtotal);
        
        if (currentSubtotal == null || currentSubtotal.compareTo(BigDecimal.ZERO) <= 0) {
            return DiscountResult.noDiscount(currentSubtotal);
        }
        
        // 查询当前生效的满减规则（启用且在有效期内）
        List<ThresholdDiscountRuleDTO> allRules = getEffectiveThresholdDiscounts();
        
        if (allRules.isEmpty()) {
            log.debug("没有满减规则");
            return DiscountResult.noDiscount(currentSubtotal);
        }
        
        BigDecimal totalDiscount = BigDecimal.ZERO;
        StringBuilder descBuilder = new StringBuilder();
        String appliedRuleId = null;
        String appliedRuleName = null;
        
        for (ThresholdDiscountRuleDTO rule : allRules) {
            // 委托PricingService计算满减减免金额（封装所有计算和判断逻辑）
            Money reductionMoney = pricingService.calculateThresholdReduction(
                Money.of(currentSubtotal),
                Money.of(originalSubtotal),
                Money.of(rule.getThresholdAmount().getAmount()),
                Money.of(rule.getDiscountAmount().getAmount()),
                Boolean.TRUE.equals(rule.getStackable()),
                Boolean.TRUE.equals(rule.getThresholdUseOriginalPrice())
            );
            
            BigDecimal ruleDiscount = reductionMoney.getDisplayAmount();
            
            // 未满足门槛，跳过此规则
            if (ruleDiscount.compareTo(BigDecimal.ZERO) == 0) {
                log.debug("未达到满减门槛，跳过规则: ruleId={}", rule.getId());
                continue;
            }
            
            // 累加减免金额
            totalDiscount = totalDiscount.add(ruleDiscount);
            
            // 生成满减描述
            if (descBuilder.length() > 0) {
                descBuilder.append("、");
            }
            
            // 计算次数用于描述
            int times = Boolean.TRUE.equals(rule.getStackable()) ? 
                pricingService.calculateThresholdCount(
                    Money.of(Boolean.TRUE.equals(rule.getThresholdUseOriginalPrice()) ? originalSubtotal : currentSubtotal),
                    Money.of(rule.getThresholdAmount().getAmount())) : 1;
            
            descBuilder.append(generateThresholdDiscountDescription(
                rule.getThresholdAmount().getAmount(), 
                rule.getDiscountAmount().getAmount(), 
                times, 
                rule.getStackable()));
            
            // 记录第一个生效的规则信息
            if (appliedRuleId == null) {
                appliedRuleId = rule.getId();
                appliedRuleName = "满减优惠";
            }
            
            log.debug("满减规则生效: ruleId={}, reduction={}", rule.getId(), ruleDiscount);
            
            // 如果不可叠加，只取第一个满足条件的规则
            if (!Boolean.TRUE.equals(rule.getStackable())) {
                break;
            }
        }
        
        // 折扣金额不能超过当前小计
        if (totalDiscount.compareTo(currentSubtotal) > 0) {
            totalDiscount = currentSubtotal;
        }
        
        if (totalDiscount.compareTo(BigDecimal.ZERO) == 0) {
            return DiscountResult.noDiscount(currentSubtotal);
        }
        
        BigDecimal discountedAmount = currentSubtotal.subtract(totalDiscount);
        String description = descBuilder.toString();
        
        log.debug("满减折扣计算结果: currentSubtotal={}, totalDiscount={}, description='{}'", 
                 currentSubtotal, totalDiscount, description);
        
        return DiscountResult.withDiscount(currentSubtotal, discountedAmount, description,
                                         appliedRuleId, appliedRuleName, "THRESHOLD");
    }
    
    /**
     * 生成满减折扣描述
     * 
     * @param thresholdAmount 门槛金额
     * @param discountAmount 减免金额
     * @param times 叠加次数
     * @param stackable 是否可叠加
     * @return 满减描述字符串
     */
    private String generateThresholdDiscountDescription(BigDecimal thresholdAmount, BigDecimal discountAmount, 
                                                       int times, Boolean stackable) {
        if (Boolean.TRUE.equals(stackable) && times > 1) {
            return String.format("满%s减%s（已减%d次）", 
                               thresholdAmount.stripTrailingZeros().toPlainString(),
                               discountAmount.stripTrailingZeros().toPlainString(),
                               times);
        } else {
            return String.format("满%s减%s", 
                               thresholdAmount.stripTrailingZeros().toPlainString(),
                               discountAmount.stripTrailingZeros().toPlainString());
        }
    }
    
    @Override
    @Transactional(readOnly = true)
    public boolean isRuleEffective(String ruleId, LocalDateTime currentTime) {
        log.debug("检查规则是否有效: ruleId={}, currentTime={}", ruleId, currentTime);
        
        PricingRule rule = pricingRuleRepository.findByIdAndNotDeleted(ruleId).orElse(null);
        
        if (rule == null || !rule.getEnabled()) {
            return false;
        }
        
        LocalDateTime checkTime = currentTime != null ? currentTime : LocalDateTime.now();
        
        // 修复时间判断逻辑：使用 !isAfter 和 !isBefore 以包含边界时间点
        // validFrom <= checkTime && (validTo == null || validTo >= checkTime)
        boolean isEffective = !rule.getValidFrom().isAfter(checkTime) 
                && (rule.getValidTo() == null || !rule.getValidTo().isBefore(checkTime));
        
        log.debug("规则有效性检查结果: ruleId={}, isEffective={}", ruleId, isEffective);
        
        return isEffective;
    }
    
    // ==================== 私有辅助方法 ====================
    
    /**
     * 禁用冲突的单品折扣规则（同商品）
     * 同优先级、同商品，只能有一个规则 enabled=true
     */
    private void disableConflictingItemDiscounts(String currentRuleId, Integer priority) {
        // 获取当前规则的商品ID
        List<ItemDiscountRule> currentItemRules = itemDiscountRuleRepository
                .findByRuleIdAndIsDeleted(currentRuleId, false);
        if (currentItemRules.isEmpty()) {
            return;
        }
        ItemDiscountRule currentItemRule = currentItemRules.get(0);
        String productId = currentItemRule.getProductId();
        
        // 查找同商品、同优先级、已启用的其他规则
        List<PricingRule> conflictRules = pricingRuleRepository
                .findByTypeAndPriorityAndEnabledAndIsDeleted(
                        PricingRuleType.ITEM_DISCOUNT, priority, true, false);
        
        for (PricingRule conflictRule : conflictRules) {
            if (conflictRule.getId().equals(currentRuleId)) {
                continue;
            }
            
            // 检查是否是同一商品
            List<ItemDiscountRule> conflictItemRules = itemDiscountRuleRepository
                    .findByRuleIdAndIsDeleted(conflictRule.getId(), false);
            
            if (!conflictItemRules.isEmpty()) {
                ItemDiscountRule conflictItemRule = conflictItemRules.get(0);
                if (conflictItemRule.getProductId().equals(productId)) {
                    // 禁用冲突规则
                    conflictRule.setEnabled(false);
                    conflictRule.setUpdatedAt(LocalDateTime.now());
                    pricingRuleRepository.save(conflictRule);
                    
                    log.info("自动禁用冲突的单品折扣规则: ruleId={}, name={}, productId={}", 
                            conflictRule.getId(), conflictRule.getName(), productId);
                }
            }
        }
    }
    
    /**
     * 禁用冲突的满减规则（同优先级）
     * 同优先级只能有一个满减规则 enabled=true
     */
    private void disableConflictingThresholdDiscounts(String currentRuleId, Integer priority) {
        // 查找同优先级、已启用的其他满减规则
        List<PricingRule> conflictRules = pricingRuleRepository
                .findByTypeAndPriorityAndEnabledAndIsDeleted(
                        PricingRuleType.THRESHOLD_DISCOUNT, priority, true, false);
        
        for (PricingRule conflictRule : conflictRules) {
            if (!conflictRule.getId().equals(currentRuleId)) {
                // 禁用冲突规则
                conflictRule.setEnabled(false);
                conflictRule.setUpdatedAt(LocalDateTime.now());
                pricingRuleRepository.save(conflictRule);
                
                log.info("自动禁用冲突的满减规则: ruleId={}, name={}", 
                        conflictRule.getId(), conflictRule.getName());
            }
        }
    }
}

